package io.gitee.yth.design.pattern.test.core.pattern.behavioral.command;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 对于不能撤销和不需要参数的简单命令，可以模板来参数化这个命令的接收者
 *
 * @author yth
 * @since 2023-04-29-0:48
 */
public class SimpleCommand<T> implements Command {

    private final T receiver;
    private final Method action;

    public SimpleCommand(T receiver, String methodName) throws NoSuchMethodException {
        final Method action = receiver.getClass().getDeclaredMethod(methodName);
        if (!action.isAccessible()) action.setAccessible(true);
        this.receiver = receiver;
        this.action = action;
    }

    @Override
    public void execute() {
        try {
            action.invoke(receiver);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}
